package com.atguigu.realtime.sink;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.bean.TableProcess;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.DruidDSUtil;
import com.atguigu.realtime.util.RedisUtil;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import redis.clients.jedis.Jedis;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author lzc
 * @Date 2022/5/18 13:57
 */
public class PhoenixSink extends RichSinkFunction<Tuple2<JSONObject, TableProcess>> {
    
    private DruidPooledConnection conn;
    private Jedis redisClient;
    
    @Override
    public void open(Configuration parameters) throws Exception {
        DruidDataSource dataSource = DruidDSUtil.createDataSource(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL);
        conn = dataSource.getConnection();
        
        redisClient = RedisUtil.getRedisClient();
        
    }
    
    @Override
    public void close() throws Exception {
        if (conn != null) {
            conn.close();
        }
    }
    
    @Override
    public void invoke(Tuple2<JSONObject, TableProcess> t,
                       Context context) throws Exception {
        
        // 1. 数据写入到phoenix
        writeToPhoenix(t);
        
        // 2. 删除缓存
        delCache(t);
        
    }
    
    // 删除缓存
    private void delCache(Tuple2<JSONObject, TableProcess> t) {
        JSONObject data = t.f0;
        TableProcess tp = t.f1;
        
        String key = tp.getSink_table() + ":" + data.getString("id");
        redisClient.del(key);
        
    }
    
    private void writeToPhoenix(Tuple2<JSONObject, TableProcess> t) throws SQLException {
        JSONObject data = t.f0;
        TableProcess tp = t.f1;
        // 1. sql语句, 一定有占位符
        // upsert into t(a,b,c)values(?,?,?)
        StringBuilder sql = new StringBuilder();
        sql
            .append("upsert into ")
            .append(tp.getSink_table())
            .append("(")
            .append(tp.getSink_columns())
            .append(")values(")
            .append(tp.getSink_columns().replaceAll("[^,]+", "?"))
            .append(")");
        System.out.println("插入语句:" + sql.toString());
        // 2. 获取预处理语句
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        // 3. 给占位符值 TODO
        String[] cs = tp.getSink_columns().split(",");
        for (int i = 0; i < cs.length; i++) {
            String columnName = cs[i];
            Object v = data.get(columnName);  // 如果在mysql中某个字段的值是null, 则这里会获取null
            ps.setString(i + 1, v == null ? null : v.toString());  // v + ""   null + "" = "null"
        }
        
        // 4. 执行
        ps.execute();
        
        // 5. 提交
        conn.commit();
        
        // 6. 关闭预处理
        ps.close();
    }
}
